<template>
    <div class="floating-icon" :style="{
        left: posX + 'px',
        top: posY + 'px',
        cursor: isDragging ? 'move' : 'pointer',
    }" @mousedown="startDrag" @mouseup="stopDrag">
        <slot>
            <el-popover placement="top-start" title="我是FF,您的专属AI" :width="200" trigger="hover" content="点击我开始对话吧!"
                :show-after="1000">
                <template #reference>
                    <img src="/ai1.png" class="aiIcons" />
                </template>
            </el-popover>
        </slot>
        <el-drawer 
            v-model="visible" 
            :show-close="false" 
            :modal="false" 
            :size="drawerSize"
            :before-close="handleClose"
            class="resizable-drawer"
            direction="rtl"
            :with-header="true"
        >
            <template #header="{ close, titleId, titleClass }">
                <div class="drawer-header">
                    <h4 :id="titleId" :class="titleClass">您好！我是你的专属AI机器人!</h4>
                    <el-button type="danger" @click="close">
                        <el-icon class="el-icon--left">
                            <CircleCloseFilled />
                        </el-icon>
                        关闭
                    </el-button>
                </div>
            </template>
            
            <div class="drawer-content">
                <!-- 聊天内容区域 -->
                <div class="chat-content">
                    <!-- 这里可以添加聊天消息列表 -->
                    <div v-for="(message, index) in chatMessages" :key="index" 
                        :class="['message', message.type === 'user' ? 'message-user' : 'message-ai']">
                        {{ message.content }}
                    </div>
                </div>
                
                <!-- 底部输入区域 -->
                <div class="input-area">
                    <div class="model-selector">
                        <el-select 
                            v-model="selectedModel" 
                            class="model-select"
                            @change="handleModelChange"
                        >
                            <el-option
                                v-for="model in aiModels"
                                :key="model.value"
                                :label="model.label"
                                :value="model.value"
                            />
                        </el-select>
                    </div>
                    
                    <div class="input-wrapper">
                        <el-input
                            v-model="inputContent"
                          
                            :rows="2"
                            :maxlength="500"
                            placeholder="请输入问题"
                            resize="none"
                            show-word-limit
                        />
                        <el-button 
                            type="primary" 
                            class="send-button"
                            :disabled="!inputContent.trim()"
                            @click="handleSend"
                        >
                            发送
                            <el-icon class="el-icon--right">
                                <el-icon-position />
                            </el-icon>
                        </el-button>
                    </div>
                </div>
            </div>
            
            <!-- 拖拽调整大小的手柄 -->
            <div 
                class="resize-handle"
                @mousedown="startResize"
            ></div>
        </el-drawer>
    </div>
</template>

<script setup>
import { CircleCloseFilled, Position as ElIconPosition } from '@element-plus/icons-vue';
import { onMounted, onUnmounted, ref } from 'vue';

const props = defineProps({
    initialX: {
        type: Number,
        default: 20,
    },
    initialY: {
        type: Number,
        default: 20,
    },
});

// 状态变量
const posX = ref(props.initialX);
const posY = ref(props.initialY);
const isDragging = ref(false);
const isLongPress = ref(false);
const visible = ref(false);
const drawerSize = ref('55%');
const isResizing = ref(false);
const inputContent = ref('');
const chatMessages = ref([]);

// AI模型配置
const aiModels = ref([
    { label: 'ChatGPT', value: 'chatGpt' },
    { label: 'Claude', value: 'claude' },
    { label: 'Gemini', value: 'gemini' }
]);
const selectedModel = ref('chatGpt');

// 拖拽相关变量
let dragStartX = 0;
let dragStartY = 0;
let longPressTimer = null;
let initialClickX = 0;
let initialClickY = 0;
let initialDrawerWidth = 0;

// 发送消息
const handleSend = () => {
    if (inputContent.value.trim()) {
        // 添加用户消息
        chatMessages.value.push({
            type: 'user',
            content: inputContent.value.trim()
        });
        
        // 这里可以添加发送到后端的逻辑
        // 模拟AI回复
        setTimeout(() => {
            chatMessages.value.push({
                type: 'ai',
                content: `使用 ${selectedModel.value} 回复: ${inputContent.value}`
            });
        }, 500);
        
        // 清空输入
        inputContent.value = '';
    }
};

// 拖拽图标相关方法
const startDrag = (event) => {
    if (event.button === 0) {
        event.preventDefault();
        clearTimeout(longPressTimer);

        initialClickX = event.clientX;
        initialClickY = event.clientY;

        longPressTimer = setTimeout(() => {
            isLongPress.value = true;
            isDragging.value = true;
            dragStartX = initialClickX - posX.value;
            dragStartY = initialClickY - posY.value;
            document.addEventListener('mousemove', drag);
        }, 200);

        document.addEventListener('mouseup', stopDrag);
        document.addEventListener('mouseleave', stopDrag);
    }
};

const drag = (event) => {
    if (isDragging.value) {
        const newX = event.clientX - dragStartX;
        const newY = event.clientY - dragStartY;

        const iconWidth = 60;
        const iconHeight = 60;

        posX.value = Math.max(0, Math.min(newX, window.innerWidth - iconWidth));
        posY.value = Math.max(0, Math.min(newY, window.innerHeight - iconHeight));
    }
};

const stopDrag = (event) => {
    clearTimeout(longPressTimer);

    document.removeEventListener('mousemove', drag);
    document.removeEventListener('mouseup', stopDrag);
    document.removeEventListener('mouseleave', stopDrag);

    const movementDistance = Math.sqrt(
        Math.pow(event.clientX - initialClickX, 2) + Math.pow(event.clientY - initialClickY, 2)
    );

    if (movementDistance < 5 && !isLongPress.value) {
        handleClick();
    }

    isDragging.value = false;
    isLongPress.value = false;
};

// 抽屉大小调整相关方法
const startResize = (event) => {
    event.preventDefault();
    isResizing.value = true;
    initialDrawerWidth = parseInt(drawerSize.value);
    document.addEventListener('mousemove', handleResize);
    document.addEventListener('mouseup', stopResize);
};

const handleResize = (event) => {
    if (isResizing.value) {
        const newWidth = Math.max(300, Math.min(window.innerWidth * 0.9, window.innerWidth - event.clientX));
        drawerSize.value = `${(newWidth / window.innerWidth) * 100}%`;
    }
};

const stopResize = () => {
    isResizing.value = false;
    document.removeEventListener('mousemove', handleResize);
    document.removeEventListener('mouseup', stopResize);
};

// 其他方法
const handleClick = () => {
    visible.value = true;
};

const handleModelChange = (value) => {
    console.log('Selected model changed to:', value);
    // 这里可以添加模型切换后的逻辑
};

const handleClose = (done) => {
    done();
};

// 生命周期钩子
onMounted(() => {
    window.addEventListener('resize', () => {
        const iconWidth = 60;
        const iconHeight = 60;
        posX.value = Math.min(posX.value, window.innerWidth - iconWidth);
        posY.value = Math.min(posY.value, window.innerHeight - iconHeight);
    });
});

onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
});
</script>

<style lang="scss" scoped>
.floating-icon {
    position: fixed;
    user-select: none;
    z-index: 1000;

    .aiIcons {
        width: 60px;
        border-radius: 50%;

        &:hover {
            box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.5);
            transform: scale(1.1);
        }
    }
}

.resizable-drawer {
    :deep(.el-drawer__body) {
        padding: 0;
        display: flex;
        flex-direction: column;
        height: 100%;
    }

    :deep(.el-drawer__container) {
        position: relative;
    }
}

.drawer-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
}

.drawer-content {
    display: flex;
    flex-direction: column;
    height: 100%;
    position: relative;
}

.chat-content {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    min-height: 70%;

    .message {
        margin: 10px 0;
        padding: 10px;
        border-radius: 8px;
        max-width: 80%;
    }

    .message-user {
        background-color: #e3f2fd;
        margin-left: auto;
    }

    .message-ai {
        background-color: #f5f5f5;
        margin-right: auto;
    }
}

.input-area {
    max-height: 30%;
    padding: 20px;
    border-top: 1px solid #eee;
    background-color: #fff;

    .model-selector {
        margin-bottom: 10px;
    }

    .model-select {
        width: 200px;
    }

    .input-wrapper {
        position: relative;
        display: flex;
        gap: 10px;

        :deep(.el-textarea__inner) {
            resize: none;
            min-height: 60px;
            max-height: calc(30vh - 100px);
        }

        .send-button {
            align-self: flex-end;
        }
    }
}

.resize-handle {
    position: absolute;
    right: 0;
    top: 0;
    bottom: 0;
    width: 5px;
    cursor: ew-resize;
    background-color: transparent;

    &:hover {
        background-color: #e0e0e0;
    }
}
</style>